package com.innovation.ic.im.end.web.controller.im_erp9;

import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.im.end.base.pojo.ApiResult;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.Constants;
import com.innovation.ic.im.end.base.thread.data.InsertUserCurrentDataToRedisThread;
import com.innovation.ic.im.end.web.controller.AbstractController;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 账号和账号对话的关系API
 */
@Api(value = "账号和账号对话的关系API", tags = "ChatPairController")
@RestController
@RequestMapping("/api/v1/chatPair")
@DefaultProperties(defaultFallback = "defaultFallback")
public class ChatPairController extends AbstractController {
    private static final Logger log = LoggerFactory.getLogger(RefGroupAccountController.class);

    /**
     * 将某个用户对某个用户设置为置顶
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "将某个用户对某个用户设置为置顶")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fromUserAccount", value = "用户账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "toUserAccount", value = "用户账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态。1表示设置为置顶。0表示取消置顶", required = true, dataType = "Integer")
    })
    @RequestMapping(value = "/topping/{fromUserAccount}/{toUserAccount}/{status}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> topping(@PathVariable("fromUserAccount") String fromUserAccount,
                                                      @PathVariable("toUserAccount") String toUserAccount,
                                                      @PathVariable("status") Integer status,
                                                      HttpServletRequest request, HttpServletResponse response) throws InterruptedException {
        if (StringUtils.isEmpty(fromUserAccount) || StringUtils.isEmpty(toUserAccount)
                || null == status) {
            String message = "调用接口【/api/v1/chatPair/topping/{fromUserAccount}/{toUserAccount}/{status}时，参数fromUserAccount、toUserAccount和status不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<Boolean>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        ServiceResult<Boolean> serviceResult = chatPairService.updateCharPair(fromUserAccount, toUserAccount, status);
        if(serviceResult.getResult()){
            // 将用户最近联系人的信息导入redis
            List<String> userNameList = new ArrayList<>();
            userNameList.add(fromUserAccount);
            InsertUserCurrentDataToRedisThread insertUserCurrentDataToRedisThread = new InsertUserCurrentDataToRedisThread(userNameList, redisManager, userGroupService, Boolean.TRUE, rabbitMqParamConfig);
            threadPoolManager.execute(insertUserCurrentDataToRedisThread);
        }

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 用户fromUserAccount和用户toUserAccount在某个时间之前的聊天记录，对fromUserAccount不可见
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "用户fromUserAccount和用户toUserAccount在某个时间之前的聊天记录，对fromUserAccount不可见")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fromUserAccount", value = "用户账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "toUserAccount", value = "用户账号", required = true, dataType = "String")
    })
    @RequestMapping(value = "/invisible/{fromUserAccount}/{toUserAccount}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> invisible(@PathVariable("fromUserAccount") String fromUserAccount,
                                                      @PathVariable("toUserAccount") String toUserAccount,
                                                      HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(fromUserAccount) || StringUtils.isEmpty(toUserAccount)) {
            String message = "调用接口【/api/v1/chatPair/invisible/{fromUserAccount}/{toUserAccount}时，参数fromUserAccount、toUserAccount不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 根据用户设置一对一聊天内容不可见时间
        Map<String, Object> map = new HashMap<>();
        map.put(Constants.FROM_USER_ACCOUNT, fromUserAccount);
        map.put(Constants.TO_USER_ACCOUNT, toUserAccount);
        ServiceResult<Boolean> result = chatPairService.invisibleChatRecordSet(map);

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        apiResult.setResult(result.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 将用户fromUserAccount从用户toUserAccount的最近联系人中删除，并清除fromUserAccount关于toUserAccount的聊天记录
     * @return 返回删除结果
     */
    @HystrixCommand
    @ApiOperation(value = "将用户fromUserAccount从用户toUserAccount的最近联系人中删除，并清除fromUserAccount关于toUserAccount的聊天记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fromUserAccount", value = "当前登录用户账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "toUserAccount", value = "要从最近联系人删除的用户账号", required = true, dataType = "String")
    })
    @RequestMapping(value = "/deleteChat/{fromUserAccount}/{toUserAccount}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> deleteChat(@PathVariable("fromUserAccount") String fromUserAccount,
                                               @PathVariable("toUserAccount") String toUserAccount,
                                               HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(fromUserAccount) || StringUtils.isEmpty(toUserAccount)) {
            String message = "调用接口【/api/v1/chatPair/deleteChat/{fromUserAccount}/{toUserAccount}时，参数fromUserAccount、toUserAccount不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 删除最近联系人并清除聊天记录
        Map<String, Object> map = new HashMap<>();
        map.put(Constants.FROM_USER_ACCOUNT, fromUserAccount);
        map.put(Constants.TO_USER_ACCOUNT, toUserAccount);
        ServiceResult<Boolean> result = chatPairService.deleteChat(map);
        if(result.getResult()){
            // 将用户最近联系人的信息导入redis
            List<String> userNameList = new ArrayList<>();
            userNameList.add(fromUserAccount);
            InsertUserCurrentDataToRedisThread insertUserCurrentDataToRedisThread = new InsertUserCurrentDataToRedisThread(userNameList, redisManager, userGroupService, Boolean.TRUE, rabbitMqParamConfig);
            threadPoolManager.execute(insertUserCurrentDataToRedisThread);
        }

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        apiResult.setResult(result.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 更新用户fromUserAccount和用户toUserAccount的最近联系时间
     * @return 返回更新结果
     */
    @HystrixCommand
    @ApiOperation(value = "更新用户fromUserAccount和用户toUserAccount的最近联系时间")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fromUserAccount", value = "发送消息的用户账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "toUserAccount", value = "接收消息的用户账号", required = true, dataType = "String")
    })
    @RequestMapping(value = "/updateLastContactTime/{fromUserAccount}/{toUserAccount}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> updateLastContactTime(@PathVariable("fromUserAccount") String fromUserAccount,
                                                      @PathVariable("toUserAccount") String toUserAccount, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(fromUserAccount) || StringUtils.isEmpty(toUserAccount)) {
            String message = "调用接口【/api/v1/chatPair/updateLastContactTime/{fromUserAccount}/{toUserAccount}时，参数fromUserAccount、toUserAccount不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 根据用户更新最近联系时间
        ServiceResult<Boolean> serviceResult = chatPairService.updateAccountLastContactTime(fromUserAccount, toUserAccount);
        if(serviceResult.getResult()){
            // 将用户最近联系人的信息导入redis
            List<String> userNameList = new ArrayList<>();
            userNameList.add(toUserAccount);
            InsertUserCurrentDataToRedisThread insertUserCurrentDataToRedisThread = new InsertUserCurrentDataToRedisThread(userNameList, redisManager, userGroupService, Boolean.TRUE, rabbitMqParamConfig);
            threadPoolManager.execute(insertUserCurrentDataToRedisThread);
        }

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        apiResult.setResult(Boolean.TRUE);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 设置某个用户对某个用户消息免打扰
     * @return 返回结果
     */
    @HystrixCommand
    @ApiOperation(value = "设置某个用户对某个用户消息免打扰")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fromUserAccount", value = "用户账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "toUserAccount", value = "用户账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态。1表示设置为消息免打扰。0表示取消消息免打扰", required = true, dataType = "Integer")
    })
    @RequestMapping(value = "/noReminder/{fromUserAccount}/{toUserAccount}/{status}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> noReminder(@PathVariable("fromUserAccount") String fromUserAccount,
                                                         @PathVariable("toUserAccount") String toUserAccount,
                                                         @PathVariable("status") Integer status,
                                                         HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(fromUserAccount) || StringUtils.isEmpty(toUserAccount) || status == null) {
            String message = "调用接口【/api/v1/chatPair/noReminder/{fromUserAccount}/{toUserAccount}/{status}时，参数fromUserAccount、toUserAccount、status不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 设置某个用户对某个用户消息免打扰
        ServiceResult<Boolean> serviceResult = chatPairService.noReminder(fromUserAccount, toUserAccount, status);
        if(serviceResult.getResult()){
            // 将用户最近联系人的信息导入redis
            List<String> userNameList = new ArrayList<>();
            userNameList.add(toUserAccount);
            InsertUserCurrentDataToRedisThread insertUserCurrentDataToRedisThread = new InsertUserCurrentDataToRedisThread(userNameList, redisManager, userGroupService, Boolean.TRUE, rabbitMqParamConfig);
            threadPoolManager.execute(insertUserCurrentDataToRedisThread);
        }

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(serviceResult.getSuccess());
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(serviceResult.getMessage());
        apiResult.setResult(serviceResult.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 更新某个用户与某个用户的聊天页面打开状态
     * @return 返回结果
     */
    @HystrixCommand
    @ApiOperation(value = "更新某个用户与某个用户的聊天页面打开状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fromUserAccount", value = "发送消息的用户账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "toUserAccount", value = "接收消息的用户账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态。0表示聊天窗口关闭，1表示聊天窗口打开", required = true, dataType = "Integer")
    })
    @RequestMapping(value = "/updateChatPageStatus/{fromUserAccount}/{toUserAccount}/{status}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> updateChatPageStatus(@PathVariable("fromUserAccount") String fromUserAccount,
                                                @PathVariable("toUserAccount") String toUserAccount,
                                                @PathVariable("status") Integer status,
                                                HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(fromUserAccount) || StringUtils.isEmpty(toUserAccount) || status == null) {
            String message = "调用接口【/api/v1/chatPair/updateChatPageStatus/{fromUserAccount}/{toUserAccount}/{status}时，参数fromUserAccount、toUserAccount、status不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 更新某个用户与某个用户的聊天页面打开状态
        ServiceResult<Boolean> serviceResult = chatPairService.updateChatPageStatus(fromUserAccount, toUserAccount, status);

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(serviceResult.getSuccess());
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(serviceResult.getMessage());
        apiResult.setResult(serviceResult.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }
}